package com.ycsj.goldmedalnewconcept.teacher.adapter;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ycsj.common.manager.MediaPlayerManager;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.student.adapter.RvShowPicAdapter;
import com.ycsj.goldmedalnewconcept.student.bean.StHomeWorkInfo;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherLookStudentListActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 老师端--历史练习--列表适配器
 * Created by Administrator on 2018/5/8 0008.
 */
public class HistoryWorkRvAdapter extends BaseQuickAdapter<StHomeWorkInfo.HomeworkBean, BaseViewHolder> {

    private Context context;

    //记录当前点击的位置
    public int mCurrentPosition = -1;

    //整个数据源
    private List<StHomeWorkInfo.HomeworkBean> datas;

    //条目的播放进度
    private int currentPlayProgress = 0;

    private Handler handler = new Handler();

    public HistoryWorkRvAdapter(Context context, int layoutResId, @Nullable List<StHomeWorkInfo.HomeworkBean> data) {
        super(layoutResId, data);
        this.context = context;
        this.datas = data;
    }

    @Override
    protected void convert(final BaseViewHolder holder, final StHomeWorkInfo.HomeworkBean info) {

        //创建时间
        TextView tvCreateTime = holder.getView(R.id.tv_create_time);

        //根据服务器返回的状态来决定APP练习和题库练习的整体布局显示状态
        //APP练习的整体布局
        LinearLayout llAppHomework = holder.getView(R.id.ll_app_homework);

        //上次练习点评的整体布局
        LinearLayout llLastHomeWork = holder.getView(R.id.ll_last_homework);

        //上次练习点评
        TextView tvLastHomeWork = holder.getView(R.id.tv_last_homework);

        //本次练习的线性布局
        LinearLayout llThisHomeWork = holder.getView(R.id.ll_this_home_work);

        //本次练习
        TextView tvThisHomeWork = holder.getView(R.id.tv_this_homework);


        //查看布置练习的名单
        ImageView lvStudentList = holder.getView(R.id.lv_student_list);

        //显示布置练习图片的RecyclerView
        RecyclerView rv = holder.getView(R.id.rv);

        //语音练习
        LinearLayout llYyzy = holder.getView(R.id.ll_yyzy);

        if (TextUtils.isEmpty(info.getAUDIO_LEN()) || TextUtils.isEmpty(info.getUSER_AUDIO())) {
            //当服务器返回的语音练习的音频时长或者音频文件的Url地址为空时不显示布局
            llYyzy.setVisibility(View.GONE);
        } else {
            //显示语音练习的布局
            llYyzy.setVisibility(View.VISIBLE);

            //播放按钮
            final Button btPlay = holder.getView(R.id.bt_play);

            //设置Tag
            btPlay.setTag(holder.getLayoutPosition());

            if (info.isPlaying()) {
                //播放状态
                btPlay.setBackgroundResource(R.drawable.pause);
            } else {
                //非播放状态
                btPlay.setBackgroundResource(R.drawable.play);
            }

            //播放进度条
            final SeekBar playSeekBar = holder.getView(R.id.playSeekBar);
            playSeekBar.setTag(holder.getLayoutPosition());

            if (!TextUtils.isEmpty(info.getAUDIO_LEN())) {
                //设置SeekBar的最大进度
                String audioLen = info.getAUDIO_LEN();
                if (audioLen.endsWith("秒")) {
                    playSeekBar.setMax((int) (Double.parseDouble(audioLen.substring(0, audioLen.length() - 1)) * 1000));
                } else {
                    playSeekBar.setMax((int) (Double.parseDouble(info.getAUDIO_LEN()) * 1000));
                }
            }

            //设置进度条数据
            if (mCurrentPosition == holder.getLayoutPosition()) {
                playSeekBar.setProgress(currentPlayProgress);
            } else {
                playSeekBar.setProgress(0);
            }

            //设置不可拖动
            playSeekBar.setEnabled(false);

            //播放按钮点击事件
            btPlay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //将当前点击的位置记录下来
                    if (mCurrentPosition == holder.getLayoutPosition()) {
                        //点击的同一个条目

                        //同步按钮状态
                        info.setPlaying(!info.isPlaying());

                        notifyDataSetChanged();

                        //同步播放状态
                        if (null != MediaPlayerManager.getInstance().getPlayer() && MediaPlayerManager.getInstance().getPlayer().isPlaying()) {

                            //播放状态下点击,播放器暂停
                            MediaPlayerManager.getInstance().getPlayer().pause();

                            //handler不继续发送更新seekbar的消息
                            handler.removeCallbacksAndMessages(null);

                        } else {
                            if (info.isOver()) {

                                //还原状态
                                info.setOver(false);

                                //重新第二次播放
                                startPlay(info, btPlay, playSeekBar);

                            } else {
                                //暂停状态下点击播放
                                MediaPlayerManager.getInstance().getPlayer().start();
                                startTime(btPlay, playSeekBar);
                            }
                        }

                    } else {
                        //点击的非同一个条目
                        //记录当前点击的位置
                        mCurrentPosition = holder.getLayoutPosition();

                        //同步按钮状态
                        for (int i = 0; i < datas.size(); i++) {
                            if (i == holder.getLayoutPosition()) {
                                datas.get(i).setPlaying(true);
                            } else {
                                datas.get(i).setPlaying(false);
                            }
                        }
                        notifyDataSetChanged();

                        //播放音频
                        startPlay(info, btPlay, playSeekBar);

                    }
                }
            });
        }

        //原生练习时间
        tvCreateTime.setText(info.getSended());

        //APP练习显示
        llAppHomework.setVisibility(View.VISIBLE);

        //上次练习点评是否显示
        if (TextUtils.isEmpty(info.getCOMMENT())) {
            //上次点评为空
            llLastHomeWork.setVisibility(View.GONE);
        } else {
            llLastHomeWork.setVisibility(View.VISIBLE);
            tvLastHomeWork.setText(info.getCOMMENT());
        }

        //本次练习是否显示的操作
        //获取本次练习的图片列表集合
        List<String> homeWorkUrls = getThisHomeWorkImages(info.getImages());

        //本次练习评论为空并且本次练习的图片Url集合也为空,不显示本次练习的整体布局
        if (TextUtils.isEmpty(info.getCONTENT()) && (homeWorkUrls == null || homeWorkUrls.size() == 0)) {
            //不显示本次练习的整体布局
            llThisHomeWork.setVisibility(View.GONE);
        } else {
            //显示本次练习的整体布局
            llThisHomeWork.setVisibility(View.VISIBLE);
            //本次练习点评是否显示
            if (TextUtils.isEmpty(info.getCONTENT())) {
                tvThisHomeWork.setVisibility(View.GONE);
            } else {
                tvThisHomeWork.setVisibility(View.VISIBLE);
                tvThisHomeWork.setText(info.getCONTENT());
            }

            //本次练习点评的图片展示
            if (homeWorkUrls == null || homeWorkUrls.size() == 0) {
                rv.setVisibility(View.GONE);
            } else {
                rv.setVisibility(View.VISIBLE);
                LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
                rv.setLayoutManager(manager);
                rv.setHasFixedSize(true);
                //练习的图片
                RvShowPicAdapter adapter = new RvShowPicAdapter(context, R.layout.student_rv_show_homework, homeWorkUrls);
                rv.setAdapter(adapter);
            }
        }

        //查看布置练习的学生名单
        lvStudentList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TeacherLookStudentListActivity.goActivity(context, info.getUSER_CLASS() + "", info.getROW_ID() + "");
            }
        });
    }

    /**
     * 开始播放
     *
     * @param info
     * @param btPlay
     * @param playSeekBar
     */
    private void startPlay(final StHomeWorkInfo.HomeworkBean info, final Button btPlay, final SeekBar playSeekBar) {
        //同步播放状态
        //进行音频的播放
        MediaPlayerManager.getInstance().play(info.getUSER_AUDIO(),
                new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                    }
                }, new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        info.setPlaying(false);
                        notifyDataSetChanged();
                        MediaPlayerManager.getInstance().stop();
                        handler.removeCallbacksAndMessages(null);

                        info.setOver(true);

                        //重置当前进度
                        currentPlayProgress = 0;

                        if ((int) btPlay.getTag() == mCurrentPosition) {
                            playSeekBar.setProgress(currentPlayProgress);
                        }
                    }
                }, new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                        //播放出错
                        info.setPlaying(false);
                        notifyDataSetChanged();
                        MediaPlayerManager.getInstance().stop();
                        handler.removeCallbacksAndMessages(null);
                        //重置当前进度
                        currentPlayProgress = 0;

                        if ((int) btPlay.getTag() == mCurrentPosition) {
                            playSeekBar.setProgress(currentPlayProgress);
                        }
                        return false;
                    }
                });

        //重置当前进度
        currentPlayProgress = 0;

        if ((int) btPlay.getTag() == mCurrentPosition) {
            playSeekBar.setProgress(currentPlayProgress);
        }

        //开启定时器
        startTime(btPlay, playSeekBar);
    }

    /**
     * 开启定时器的方法
     *
     * @param btPlay
     * @param playSeekBar
     */
    private void startTime(final Button btPlay, final SeekBar playSeekBar) {

        //Handler实现方法
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //获取播放器的播放进度
                currentPlayProgress = MediaPlayerManager.getInstance().getPlayer().getCurrentPosition();

                if ((int) btPlay.getTag() == mCurrentPosition) {
                    if (currentPlayProgress >= MediaPlayerManager.getInstance().getPlayer().getDuration()) {
                        currentPlayProgress = 0;
                        playSeekBar.setProgress(currentPlayProgress);
                    } else {
                        LogUtils.iTag("test", "当前进度是:" + currentPlayProgress);
                        playSeekBar.setProgress(currentPlayProgress);
                    }
                }
                handler.postDelayed(this, 50);

            }
        }, 50);
    }

    /**
     * 返回本次练习的图片集合方法
     *
     * @param images
     * @return
     */
    private List<String> getThisHomeWorkImages(StHomeWorkInfo.HomeworkBean.ImagesBean images) {
        List<String> mUrls = null;
        if (images != null) {
            mUrls = new ArrayList<>();
            if (!TextUtils.isEmpty(images.getUSER_PICTURE1())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE1());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE2())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE2());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE3())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE3());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE4())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE4());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE5())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE5());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE6())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE6());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE7())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE8());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE8())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE8());
            }
            if (!TextUtils.isEmpty(images.getUSER_PICTURE9())) {
                mUrls.add(images.getURL() + images.getUSER_PICTURE9());
            }
        }
        return mUrls;
    }

    /**
     * 对外提供的释放播放器对象的方法的方法
     */
    public void releaseMediaPlayer() {

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (MediaPlayerManager.getInstance().getPlayer() != null) {
            MediaPlayerManager.getInstance().getPlayer().stop();
            MediaPlayerManager.getInstance().getPlayer().release();
        }
    }
}
